import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/Home.vue";
import { getRoute } from "@/API/lzw-API/index";
import store from "@/store";
Vue.use(VueRouter);
const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/login",
    component: () => import("../views/login/Login.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  // base: "http://xue.cnkdl.cn:23683",
  routes,
});
router.beforeEach(async (to, from, next) => {
  let token = localStorage.getItem("Authorization");
  if (store.state.route.menus.length == 0 && token) {
    let res = await getRoute();
    store.commit("route/changeMenu", res.data);
    store.state.route.menus &&
      store.state.route.menus.forEach((p) => {
        const route = {
          path: p.path,
          name: p.name,
          component: HomeView,
          children:
            p.children &&
            p.children.map((item) => ({
              path: item.path,
              name: item.name,
              component: () => import(`../views/${p.name}/${item.path}.vue`),
              children:
                item.children &&
                item.children.map((items) => ({
                  path: items.path,
                  name: items.name,
                  component: () =>
                    import(`../views/${p.name}/${item.path}/${items.path}.vue`),
                })),
            })),
        };
        router.addRoute(route);
      });
    next("/");
  } else {
    next();
  }
  // console.log(router.getRoutes());
});
export default router;
